﻿using System;
using System.Threading;
using ChatCommon;
using ChatCommon.Packets;
using ChatServer.Handler;
using Lidgren.Network;
using NetBrick.Common;
using NetBrick.Server;

namespace ChatServer
{
    class ChatExampleServer : Server
    {
        private Thread _commandThread;

        public ChatExampleServer()
            : base("ChatExample", 35565, 10)
        {
        }

        protected override void Init()
        {
            ////test if logging works
            //Log.Info("Test");
            //Log.Warn("Test");
            //Log.Error("Test");
            //Log.Severe("Test");
            Log.Info("Initializing Chat Server.");
            Packet.Instance.Register(ChatPacketCode.Authenticate, typeof(AuthenticatePacket));
            Packet.Instance.Register(ChatPacketCode.ChatMessageRequest, typeof(ChatPacket.Request));
            Packet.Instance.Register(ChatPacketCode.ChatMessageEvent, typeof(ChatPacket.Event));
            AddPacketHandler(ChatPacketCode.ChatMessageRequest, new ChatPacketHandler(this));
            AddPacketHandler(ChatPacketCode.Authenticate, new AuthenticatePacketHandler(this));
            _commandThread = new Thread(() =>
            {
                while (!Environment.HasShutdownStarted)
                {
                    var input = Console.ReadLine();
                    var chatPacket = new ChatPacket.Event("Server", input);
                    Log.LogMessage(ConsoleColor.Green, String.Format(" [Chat][{0}] ", "Server"), input);
                    BroadcastPacket(ChatPacketCode.ChatMessageEvent, chatPacket, NetDeliveryMethod.ReliableOrdered);
                }
            });
            _commandThread.Start();
        }

        protected override BasePeer CreatePeer(NetConnection connection)
        {
            return new ChatPeer(connection);
        }
    }
}
